﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GroupThreeMESProject.Service.ProcurementPlanService
{
    public class RabbitMQHelper
    {
        //public static ConnectionFactory factory;
        //private static object obj = new object();


        ////连接rabbitmq 
        ////只需要连接一次
        ////单例设计模式
        //public static IConnection GetConnection()
        //{
        //    // A  B
        //    if (factory == null)
        //    {
        //        // A B
        //        //锁
        //        //防止并发
        //        lock (obj)
        //        {
        //            //A  B
        //            if (factory == null)
        //            {
        //                factory = new ConnectionFactory
        //                {
        //                    HostName = "47.94.104.5",  //连rabbitmq 地址
        //                    Port = 15672,  //默认端口
        //                    UserName = "admin",
        //                    Password = "admin",
        //                };
        //            }
        //        }
        //    }
        //    return (IConnection)factory.CreateConnectionAsync();
        //}
        private static readonly Lazy<ConnectionFactory> lazyFactory = new Lazy<ConnectionFactory>(() => new ConnectionFactory
        {
            HostName = "47.94.104.5",  // RabbitMQ 地址
            Port = 15672,  // 默认端口
            UserName = "admin",
            Password = "admin"
        });

        // 连接RabbitMQ，单例设计模式
        public static async Task<IConnection> GetConnection()
        {
            var factory = lazyFactory.Value;
            return await factory.CreateConnectionAsync();  // 创建连接（同步方法）
        }
    }
}
